package net.logax.games.chase.prepare;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import net.logax.prepare.ObjSerializable;

/**
 * fuer das ant-script
 * 
 * @author mrduke
 * 
 */
public class ObjSerializer {
	public static class Path {
		public static String BASE = "chase/";
		public static String MODELS = "models/";
		public static String ASSETS = "assets/";
	}

	public static void main(String[] args) {
		System.out.println("getting objFiles");
		final File[] objFiles = getObjFiles();
		System.out.println("serializing objFiles");
		if(objFiles == null) {
			System.out.println("objFiles is null!");
		}
		for (File srcFile : objFiles) {
			System.out.println("serializing: '" + srcFile.getName() + "'");
			final String fileName = srcFile.getName();
			String srcFilePath = null;
			try {
				srcFilePath = srcFile.getCanonicalPath();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			if (srcFilePath != null) {

				String dstFilePath = Path.BASE + Path.ASSETS + fileName
						+ ObjSerializable.SUFFIX_SERIALIZED_OBJ;
				InputStream input = null;
				try {
					input = new BufferedInputStream(new FileInputStream(
							srcFilePath));
					List<String> lines = readLines(input);
					ObjModelBuilder builder = new ObjModelBuilder(lines);
					ObjSerializable model = builder.build();
					FileOutputStream fileOut = new FileOutputStream(dstFilePath);
					ObjectOutputStream out = new ObjectOutputStream(fileOut);
					out.writeObject(model);
					out.close();
					fileOut.close();
					System.out.println("Serialized data '" + srcFilePath
							+ "' to '" + dstFilePath + "'");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static File[] getObjFiles() {
		final File modelsDir = new File(Path.BASE + Path.MODELS);
		final FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				System.out.println("accept file");
				if (filename.endsWith(".obj")) {
					return true;
				} else {
					return false;
				}
			}
		};
		System.out.println("getfiltered obj files");
		final File[] objFiles = modelsDir.listFiles(filter);
		return objFiles;
	}

	private static List<String> readLines(InputStream in) throws IOException {
		final List<String> lines = new ArrayList<String>();
		final BufferedReader reader = new BufferedReader(new InputStreamReader(
				in));
		String line = null;
		while ((line = reader.readLine()) != null)
			lines.add(line);
		return lines;
	}
}